<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>教室管理 - 教学管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #3c5166;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .user-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }

        .menu-section {
            padding: 10px 20px;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.6);
            border-bottom: 1px solid #3c5166;
            margin-top: 15px;
        }

        .menu {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .menu li:hover {
            background-color: #3c5166;
        }

        .menu li.active {
            background-color: #3498db;
        }

        .menu a {
            color: white;
            text-decoration: none;
            display: block;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }

        .content-header h1 {
            margin: 0;
            color: #333;
            font-size: 24px;
        }

        .search-box {
            display: flex;
            width: 300px;
        }

        .search-box input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px 0 0 4px;
            outline: none;
        }

        .search-box button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 0 4px 4px 0;
            cursor: pointer;
        }

        .add-button {
            background-color: #2ecc71;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        th,
        td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f8f9fa;
            font-weight: bold;
            color: #333;
        }

        tr:hover {
            background-color: #f5f7f9;
        }

        .actions {
            display: flex;
            gap: 8px;
        }

        .edit-button,
        .delete-button {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .edit-button {
            background-color: #3498db;
            color: white;
        }

        .delete-button {
            background-color: #e74c3c;
            color: white;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 10% auto;
            padding: 20px;
            border-radius: 8px;
            width: 50%;
            max-width: 500px;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: black;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .btn-cancel,
        .btn-save {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-cancel {
            background-color: #f1f1f1;
            color: #333;
        }

        .btn-save {
            background-color: #2ecc71;
            color: white;
        }

        .logout {
            margin-top: auto;
            padding: 20px;
        }

        .logout a {
            color: #e74c3c;
            text-decoration: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>教学管理系统</h2>
                <div class="user-info" th:if="${session.user}">
                    <span th:text="${session.user.username}">admin1</span> - 管理员
                </div>
            </div>
            <div class="menu-section">基础管理</div>
            <ul class="menu">
                <li><a href="/admin/dashboard">系统概览</a></li>
                <li><a href="/admin/teachers">教师管理</a></li>
                <li><a href="/admin/students">学生管理</a></li>
                <li><a href="/admin/courses">课程管理</a></li>
                <li class="active"><a href="/admin/classrooms">教室管理</a></li>
            </ul>

            <div class="menu-section">教务管理</div>
            <ul class="menu">
                <li><a href="/admin/course-selections">选课管理</a></li>
                <li><a href="/admin/grades">成绩管理</a></li>
            </ul>

            <div class="menu-section">系统设置</div>
            <ul class="menu">
                <li><a href="/admin/profile">个人信息</a></li>
            </ul>

            <div class="logout">
                <a href="/logout">退出登录</a>
            </div>
        </div>

        <div class="content">
            <div class="content-header">
                <h1>教室管理</h1>
                <div class="search-box">
                    <input type="text" id="searchInput" placeholder="搜索教室...">
                    <button type="button" onclick="searchClassrooms()">搜索</button>
                </div>
                <button class="add-button" onclick="openAddModal()">添加教室</button>
            </div>

            <table id="classroomsTable">
                <thead>
                    <tr>
                        <th>教室ID</th>
                        <th>教学楼</th>
                        <th>容量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="classroomsList">
                    <!-- 数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加教室模态框 -->
    <div id="addModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeAddModal()">&times;</span>
            <h2>添加教室</h2>
            <div class="form-group">
                <label for="addClassroomId">教室ID</label>
                <input type="text" id="addClassroomId" name="classroomId">
            </div>
            <div class="form-group">
                <label for="addBuilding">教学楼</label>
                <input type="text" id="addBuilding" name="building">
            </div>
            <div class="form-group">
                <label for="addCapacity">容量</label>
                <input type="number" id="addCapacity" name="capacity">
            </div>
            <div class="form-actions">
                <button class="btn-cancel" onclick="closeAddModal()">取消</button>
                <button class="btn-save" onclick="addClassroom()">保存</button>
            </div>
        </div>
    </div>

    <!-- 编辑教室模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeEditModal()">&times;</span>
            <h2>编辑教室</h2>
            <div class="form-group">
                <label for="editClassroomId">教室ID</label>
                <input type="text" id="editClassroomId" name="classroomId" readonly>
            </div>
            <div class="form-group">
                <label for="editBuilding">教学楼</label>
                <input type="text" id="editBuilding" name="building">
            </div>
            <div class="form-group">
                <label for="editCapacity">容量</label>
                <input type="number" id="editCapacity" name="capacity">
            </div>
            <div class="form-actions">
                <button class="btn-cancel" onclick="closeEditModal()">取消</button>
                <button class="btn-save" onclick="updateClassroom()">保存</button>
            </div>
        </div>
    </div>

    <script>
        // 页面加载时获取所有教室
        document.addEventListener('DOMContentLoaded', function () {
            fetchClassrooms();
        });

        // 获取所有教室
        function fetchClassrooms() {
            console.log("开始获取教室列表...");
            fetch('/api/admin/classrooms', {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    console.log("获取教室列表响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('获取教室失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("成功获取教室列表数据:", data);
                    renderClassroomList(data);
                })
                .catch(error => {
                    console.error('获取教室出错:', error);
                });
        }

        // 渲染教室列表
        function renderClassroomList(classrooms) {
            console.log("开始渲染教室列表...");
            const tableBody = document.getElementById('classroomsList');
            tableBody.innerHTML = '';

            if (classrooms.length === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = '<td colspan="4" style="text-align: center;">没有找到教室</td>';
                tableBody.appendChild(emptyRow);
                console.log("教室列表为空");
                return;
            }

            classrooms.forEach(classroom => {
                // 安全转义教室ID，防止特殊字符导致问题
                const safeId = classroom.classroomId.replace(/'/g, "\\'").replace(/"/g, '\\"');
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${classroom.classroomId}</td>
                    <td>${classroom.building}</td>
                    <td>${classroom.capacity}</td>
                    <td class="actions">
                        <button class="edit-button" data-id="${safeId}">编辑</button>
                        <button class="delete-button" data-id="${safeId}">删除</button>
                    </td>
                `;
                
                // 添加点击事件监听器
                const editButton = row.querySelector('.edit-button');
                const deleteButton = row.querySelector('.delete-button');
                
                editButton.addEventListener('click', function() {
                    console.log("编辑按钮被点击，教室ID:", safeId);
                    openEditModal(safeId);
                });
                
                deleteButton.addEventListener('click', function() {
                    console.log("删除按钮被点击，教室ID:", safeId);
                    confirmDelete(safeId);
                });
                
                tableBody.appendChild(row);
            });
            console.log(`成功渲染 ${classrooms.length} 个教室`);
        }

        // 搜索教室
        function searchClassrooms() {
            const searchTerm = document.getElementById('searchInput').value.trim();
            console.log("开始搜索教室，关键词:", searchTerm);
            if (searchTerm === '') {
                fetchClassrooms();
                return;
            }

            fetch(`/api/admin/classrooms/search?term=${encodeURIComponent(searchTerm)}`, {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    console.log("搜索教室响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('搜索教室失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("搜索教室结果:", data);
                    renderClassroomList(data);
                })
                .catch(error => {
                    console.error('搜索教室出错:', error);
                });
        }

        // 打开添加教室模态框
        function openAddModal() {
            document.getElementById('addModal').style.display = 'block';
            // 清空表单
            document.getElementById('addClassroomId').value = '';
            document.getElementById('addBuilding').value = '';
            document.getElementById('addCapacity').value = '';
        }

        // 关闭添加教室模态框
        function closeAddModal() {
            document.getElementById('addModal').style.display = 'none';
        }

        // 添加教室
        function addClassroom() {
            const classroomData = {
                classroomId: document.getElementById('addClassroomId').value.trim(),
                building: document.getElementById('addBuilding').value.trim(),
                capacity: parseInt(document.getElementById('addCapacity').value)
            };

            console.log("准备添加新教室:", classroomData);

            // 简单验证
            if (!classroomData.classroomId || !classroomData.building || isNaN(classroomData.capacity)) {
                alert('请填写所有必填字段');
                return;
            }

            fetch('/api/admin/classrooms', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify(classroomData)
            })
                .then(response => {
                    console.log("添加教室响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 409) {
                            alert('教室ID已存在');
                            throw new Error('教室ID已存在');
                        }
                        return response.text().then(text => { throw new Error(text || '添加教室失败') });
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("添加教室成功:", data);
                    alert('添加教室成功');
                    closeAddModal();
                    fetchClassrooms();
                })
                .catch(error => {
                    console.error('添加教室出错:', error);
                });
        }

        // 打开编辑教室模态框
        function openEditModal(classroomId) {
            console.log("准备打开编辑教室模态框，教室ID:", classroomId);
            
            if (!classroomId) {
                console.error("教室ID为空，无法打开编辑模态框");
                alert("错误：无法获取教室信息");
                return;
            }
            
            // 显示模态框并设置加载状态
            document.getElementById('editModal').style.display = 'block';
            const modalContent = document.querySelector('#editModal .modal-content');
            const originalContent = modalContent.innerHTML;
            modalContent.innerHTML = '<div style="text-align: center; padding: 20px;">加载中...</div>';
            
            fetch(`/api/admin/classrooms/${encodeURIComponent(classroomId)}`, {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    console.log("获取教室详情响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        } else if (response.status === 404) {
                            alert('教室不存在');
                        }
                        throw new Error('获取教室详情失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(classroom => {
                    console.log("成功获取教室详情:", classroom);
                    
                    // 恢复原始内容并填充数据
                    modalContent.innerHTML = originalContent;
                    document.getElementById('editClassroomId').value = classroom.classroomId;
                    document.getElementById('editBuilding').value = classroom.building;
                    document.getElementById('editCapacity').value = classroom.capacity;
                })
                .catch(error => {
                    console.error('获取教室详情出错:', error);
                    modalContent.innerHTML = `
                        <div style="text-align: center; color: red; padding: 20px;">
                            加载失败: ${error.message}
                            <div class="form-actions" style="margin-top: 20px;">
                                <button type="button" class="btn-cancel" onclick="closeEditModal()">关闭</button>
                            </div>
                        </div>
                    `;
                });
        }

        // 关闭编辑教室模态框
        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // 更新教室
        function updateClassroom() {
            const classroomId = document.getElementById('editClassroomId').value;
            const classroomData = {
                classroomId: classroomId,
                building: document.getElementById('editBuilding').value.trim(),
                capacity: parseInt(document.getElementById('editCapacity').value)
            };

            console.log("准备更新教室:", classroomData);

            // 简单验证
            if (!classroomData.building || isNaN(classroomData.capacity)) {
                alert('请填写所有必填字段');
                return;
            }
            
            // 禁用保存按钮，防止重复提交
            const saveButton = document.querySelector('#editModal .btn-save');
            const cancelButton = document.querySelector('#editModal .btn-cancel');
            
            if (saveButton) {
                saveButton.disabled = true;
                saveButton.textContent = '保存中...';
            }
            if (cancelButton) {
                cancelButton.disabled = true;
            }

            fetch(`/api/admin/classrooms/${encodeURIComponent(classroomId)}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify(classroomData)
            })
                .then(response => {
                    console.log("更新教室响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 404) {
                            alert('教室不存在');
                            throw new Error('教室不存在');
                        }
                        return response.text().then(text => { throw new Error(text || '更新教室失败') });
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("更新教室成功:", data);
                    alert('更新教室成功');
                    closeEditModal();
                    fetchClassrooms(); // 刷新教室列表
                })
                .catch(error => {
                    console.error('更新教室出错:', error);
                    alert('更新教室失败: ' + error.message);
                })
                .finally(() => {
                    // 恢复按钮状态
                    if (saveButton) {
                        saveButton.disabled = false;
                        saveButton.textContent = '保存';
                    }
                    if (cancelButton) {
                        cancelButton.disabled = false;
                    }
                });
        }

        // 确认删除教室
        function confirmDelete(classroomId) {
            console.log("确认是否删除教室，ID:", classroomId);
            if (confirm('确定要删除这个教室吗？此操作不可撤销。')) {
                deleteClassroom(classroomId);
            }
        }

        // 删除教室
        function deleteClassroom(classroomId) {
            console.log("开始删除教室，ID:", classroomId);
            fetch(`/api/admin/classrooms/${classroomId}`, {
                method: 'DELETE',
                credentials: 'include'
            })
                .then(response => {
                    console.log("删除教室响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 404) {
                            alert('教室不存在');
                            throw new Error('教室不存在');
                        } else if (response.status === 409) {
                            alert('删除失败，该教室已被课程引用，请先解除关联');
                            throw new Error('教室正在被课程引用');
                        }
                        return response.text().then(text => { throw new Error(text || '删除教室失败') });
                    }
                    return response.text();
                })
                .then(() => {
                    console.log("删除教室成功");
                    alert('删除教室成功');
                    fetchClassrooms();
                })
                .catch(error => {
                    console.error('删除教室出错:', error);
                });
        }
    </script>
</body>

</html>